package com.ld.common.util;

import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.ld.common.model.SysLog;
import com.ld.shieldsb.common.composition.util.PKUtil;
import com.ld.shieldsb.common.core.util.useragent.UserAgentModel;
import com.ld.shieldsb.common.core.util.useragent.UserAgentUtil;
import com.ld.shieldsb.common.web.BasicService;
import com.ld.shieldsb.common.web.model.SysUser;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.common.web.util.WebUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogUtil {
    public static final BasicService service = new BasicService();

    public static void saveLogbyDB(String logType, String logTitle, HttpServletRequest request) {
        saveLogbyDB(logType, logTitle, request, true);
    }

    /**
     * 保存日志
     * 
     * @Title saveLogbyDB
     * @author 吕凯
     * @date 2018年6月14日 上午11:21:00
     * @param logType
     * @param logTitle
     * @param request
     *            void
     */
    public static void saveLogbyDB(String logType, String logTitle, HttpServletRequest request, Boolean saveDB) {
        SysUser user = Web.Util.getSessionUser(request);
        Long userid = 0L;
        String username = null;
        if (user != null) {
            userid = user.getId();
            username = user.getUserName();
        }
        saveLogbyDB(userid, username, logType, logTitle, request, saveDB);
    }

    public static void saveLogbyDB(Long userid, String username, String logType, String logTitle, HttpServletRequest request,
            Boolean saveDB) {
        saveLogbyDB(userid, username, logType, logTitle, null, request, saveDB);
    }

    public static void saveLogbyDB(Long userid, String username, String logType, String logTitle, String exceptionInfo,
            HttpServletRequest request, Boolean saveDB) {
        if (username == null) {
            username = "未知";
        }
        SysLog manageLogModel = new SysLog();
        manageLogModel.setId(PKUtil.nextId());
        manageLogModel.setLogType(logType);
        manageLogModel.setLogTitle(logTitle == null ? "" : logTitle);
        manageLogModel.setCreateBy(userid + "");
        manageLogModel.setCreateByName(username);
        manageLogModel.setCreateTime(new Date());
        manageLogModel.setRequestUri(request.getRequestURI());
        manageLogModel.setRequestMethod(request.getMethod());

        String method = (request.getMethod() + "").toLowerCase();
        String requestParams = null;
        if ("post".equals(method)) {
            Enumeration<String> enumeration = request.getParameterNames();
            Map<String, String> parameterMap = Maps.newHashMap();
            while (enumeration.hasMoreElements()) {
                String parameter = enumeration.nextElement();
                parameterMap.put(parameter, request.getParameter(parameter));
            }
            requestParams = JSON.toJSONString(parameterMap);
        } else {
            requestParams = request.getQueryString();
        }
        manageLogModel.setRequestParams(requestParams);

        manageLogModel.setDiffModifyData("");
        manageLogModel.setBizKey("");
        manageLogModel.setBizType("");
        manageLogModel.setRemoteAddr(WebUtil.getIpAddr(request)); // 获取ip
        manageLogModel.setServerAddr(request.getRequestURL().toString().replace(request.getRequestURI(), ""));
        if (exceptionInfo != null) {
            manageLogModel.setIsException(1);
            manageLogModel.setExceptionInfo(exceptionInfo);
        }
        String userAgent = request.getHeader("user-agent");
        manageLogModel.setUserAgent(userAgent);
        UserAgentModel uaModel = UserAgentUtil.getUserAgent(userAgent);
        if (uaModel != null) {
            manageLogModel.setDeviceName(uaModel.getPlatformType() + " " + uaModel.getPlatformSeries());
            manageLogModel.setBrowserName(uaModel.getBrowserType() + " " + uaModel.getBrowserVersion());
        }
        if (saveDB) {
            saveLogbyDB(manageLogModel);
        } else {
            log.warn(manageLogModel + ""); // 输出到日志
        }
    }

    /**
     * 保存日志
     * 
     * @Title saveLogbyDB
     * @author 吕凯
     * @date 2018年6月14日 上午11:21:11
     * @param manageLogModel
     *            void
     */
    public static void saveLogbyDB(SysLog manageLogModel) {
        if (manageLogModel != null) {
            try {
                service.getBaseDAO().save(manageLogModel);
            } catch (Exception e) {
                log.error("保存日志出错！", e);
            }
        }
    }

}
